import visitMonthPlanModel from "../model/visitMonthPlanModel";
import visitMonthPlanService from "./visitMonthPlanService";
import formDataService from "./formDataService";

//审批时
class ApprovalService {
    constructor() { }


    //第一步:向领导显示待审核数据
    //上级领导查询某一个月其所属所有员工的待审核计划   
    //userId:领导id month:月份
    async listMonthPlanByMonth(user:any, month: string,access_token:string) {
        let isLeaderInDepts: string = user.isLeaderInDepts || ''
        isLeaderInDepts = isLeaderInDepts.substr(1, isLeaderInDepts.length - 2)
        let arrayLeaderDepts = isLeaderInDepts.split(',')
        let leaderDepts = []
        arrayLeaderDepts.map(item => {
            // console.log(item, item.endsWith(":true"));
            if (item.endsWith(":true")) {
                // console.log(item);
                leaderDepts.push(item.substr(0, item.length - ":true".length))
            }
        })
        let json: any[] = [];
        let dataCache: any = {}
        let leaderId = ""
        let json2 = []
        let json3 = []
        let list:any=[]
        let sonData=await formDataService.getsonDept(leaderDepts,false,access_token,[])
        let son_list2=await formDataService.newArray(sonData.list)
        //跨年份问题
        // let year=moment().format('YYYY');
        // let data = await visitMonthPlanModel.find({ deptId: { $in: son_list2 }, userId: { $ne: user.userId }, month: month,year:year, planStatus: '待审核' }).sort({ planDate: 1 });
        let data = await visitMonthPlanModel.find({ deptId: { $in: son_list2 }, userId: { $ne: user.userId }, month: month, planStatus: '待审核' }).sort({ planDate: 1 });
        for (let nameindex = 0; nameindex < data.length; nameindex++) {
            let element = data[nameindex];
            if (!dataCache[element.userId]) {
                dataCache[element.userId] = {
                    userid: leaderId,//员工id
                    //userid: element.userId,//员工id
                    userName: element.user,//员工名字
                    avatar: element.avatar,//员工头像信息
                    body_cancelApply: [],//申请取消的计划
                    body_temporaryPlan: [] //申请的临时计划 
                }
            }
            let isChecked: boolean = false;
            if (element.cancelApply == '是') {//判断是否有申请取消的计划
                dataCache[element.userId].body_cancelApply.push({
                    id: element._id,
                    cancelApply: element.cancelApply,
                    user: element.user,
                    userId: element.userId,
                    deptId: element.deptId,
                    sourceId: element.sourceId,
                    month: element.month,
                    visitRecoder: element.visitRecoder,
                    mark: element.mark,
                    planDate: element.planDate,
                    consumerName: element.consumerName,
                    consumerCode: element.consumerCode,
                    rest: element.rest,
                    meeting: element.meeting,
                    plantype: element.plantype,
                    planStatus: element.planStatus,
                    customerType: element.customerType,
                    purpose: element.purpose,
                    comment: element.comment,
                    remark: element.remark,
                    isChecked: isChecked
                });
            } else if (element.cancelApply == '否' || element.cancelApply == '') {
                dataCache[element.userId].body_temporaryPlan.push({
                    id: element._id,//id
                    cancelApply: element.cancelApply,
                    user: element.user,
                    userId: element.userId,
                    deptId: element.deptId,
                    sourceId: element.sourceId,
                    month: element.month,
                    visitRecoder: element.visitRecoder,
                    mark: element.mark,
                    planDate: element.planDate,
                    consumerName: element.consumerName,
                    consumerCode: element.consumerCode,
                    rest: element.rest,
                    meeting: element.meeting,
                    plantype: element.plantype,
                    planStatus: element.planStatus,
                    customerType: element.customerType,
                    purpose: element.purpose,
                    comment: element.comment,
                    remark: element.remark,
                    isChecked: isChecked
                });
            }
        }
        for (const key in dataCache) {
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                json.push(element)
            }
        }
        return json;
    }
    
    
    //领导审批后,保存审核结果,同时更新数据库的visitMonthPlan的数据(planStatus与remark)
    async saveApprovalResult(idList: string[], result: string, month: string,leaderId: string) {
        let json: any = [];
        for (let index = 0; index < idList.length; index++) {
            let element = idList[index];
            let one_data = await visitMonthPlanModel.findById({ _id: element });
            //(二)更新visitMonthPlanModel的monthplanStatus和remark  
            if (result == "同意") { //结果为agree:同意通过 refuse:不同意
                if (one_data != null) {
                    if (one_data.cancelApply == '') {
                        await visitMonthPlanModel.update({ _id: element, comment: 2 }, { planStatus: '申请取消', remark: result, cancelApply: '否' }, { upsert: true });
                    } else if (one_data.cancelApply == '是') {
                        await visitMonthPlanModel.update({ _id: element }, { planStatus: '同意', remark: result }, { upsert: true });
                    }
                }
            } else if (result == "不同意") {
                await visitMonthPlanModel.update({ _id: element }, { planStatus: '不同意', remark: result }, { upsert: true });
            } else if (result == "驳回修改") {
                await visitMonthPlanModel.update({ _id: element, comment: 2 }, { planStatus: '待修改', remark: result }, { upsert: true });
            }
        }
    }

    //(1)员工查看审核待修改的数据----每日计划(有新计划)页面
    //userid:员工id month:月份
    async getapprovalResult(userid: string, month: string, ) {
        // console.log('员工的userid:' + userid + '-----月份:' + month);
        let json: any[] = [];
        //跨年份问题
        // let year=moment().format('YYYY');
        //let approvalResultList = await visitMonthPlanModel.find({ userId: userid, month: month,year:year, planStatus: '待修改' });
        let approvalResultList = await visitMonthPlanModel.find({ userId: userid, month: month, planStatus: '待修改' });
        for (let index = 0; index < approvalResultList.length; index++) {
            let visitMonthPlan = approvalResultList[index];
            if (visitMonthPlan.remark != '') {
                json.push({
                    id: visitMonthPlan._id,  
                    sourceId: visitMonthPlan.sourceId,  
                    visitRecoder: visitMonthPlan.visitRecoder,
                    month: visitMonthPlan.month,       
                    mark: visitMonthPlan.mark,   
                    user: visitMonthPlan.user,     
                    planDate: visitMonthPlan.planDate,
                    consumerName: visitMonthPlan.consumerName,
                    consumerCode: visitMonthPlan.consumerCode,
                    rest: visitMonthPlan.rest, 
                    meeting: visitMonthPlan.meeting,
                    plantype: visitMonthPlan.plantype,
                    planStatus: visitMonthPlan.planStatus, 
                    customerType: visitMonthPlan.customerType,
                    purpose: visitMonthPlan.purpose,
                    userId: visitMonthPlan.userId, 
                    comment: visitMonthPlan.comment,
                    cancelApply: visitMonthPlan.cancelApply,
                    remark: visitMonthPlan.remark 
                });
            }
        }
        return json;
    }


    //查看一条审核结果数据的详情
    async getApprovalResultDetail(id: string) {
        let json: any = [];
        let visitMonthPlan = await visitMonthPlanModel.findById({ _id: id });
        if (visitMonthPlan) {
            json.push({
                id: visitMonthPlan._id,  
                sourceId: visitMonthPlan.sourceId,  
                visitRecoder: visitMonthPlan.visitRecoder,
                month: visitMonthPlan.month,       
                mark: visitMonthPlan.mark,   
                user: visitMonthPlan.user,     
                planDate: visitMonthPlan.planDate,
                consumerName: visitMonthPlan.consumerName,
                consumerCode: visitMonthPlan.consumerCode,
                rest: visitMonthPlan.rest, 
                meeting: visitMonthPlan.meeting,
                plantype: visitMonthPlan.plantype,
                planStatus: visitMonthPlan.planStatus, 
                customerType: visitMonthPlan.customerType,
                purpose: visitMonthPlan.purpose,
                userId: visitMonthPlan.userId, 
                comment: visitMonthPlan.comment,
                cancelApply: visitMonthPlan.cancelApply,
                remark: visitMonthPlan.remark 
            });
        } 
        return json;
    }

    //(2)查看结果后:修改了临时计划的内容,保存
    async updateMonthplanAfterCheck(res: any, user: any) {
        let rt:any='';
        let monthplan = await visitMonthPlanModel.findById({ _id: res.id });
        if (monthplan != null) {
            await visitMonthPlanModel.update({ _id: res.id }, {
                planDate: res.planDate,
                plantype: res.plantype,
                customerType: res.customerType,
                consumerName: res.consumerName,
                consumerCode: res.consumerCode,
                channel: res.channel,
                planStatus: '待审核',
                purpose: res.purpose
            }, { upsert: true });
            rt=await visitMonthPlanModel.findById({ _id: res.id });
        } else {
           rt= await visitMonthPlanService.saveTemporaryPlan(res, user);
        }
        // console.log(res.userid + '号员工待修改事项已经修改完成并保存完毕!!!!!!!!')
        return rt;
    }







}
let approval = new ApprovalService();
export default approval;